package com.lhfeiyu.action.back.shop;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.config.Page;
import com.lhfeiyu.config.Table;
import com.lhfeiyu.po.base.BaseAdmin;
import com.lhfeiyu.po.base.BaseGoods;
import com.lhfeiyu.po.base.BaseGoodsPicture;
import com.lhfeiyu.service.base.BaseAA_UtilService;
import com.lhfeiyu.service.base.BaseGoodsPictureService;
import com.lhfeiyu.service.base.BaseGoodsService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;

@Controller
@RequestMapping(value="/back")
public class BackGoodsAction {
	@Autowired
	private BaseGoodsService goodsService;
	@Autowired
	private BaseAA_UtilService utilService;
	@Autowired
	private BaseGoodsPictureService goodsPictureService;
	private static Logger logger = Logger.getLogger("R");
	
	@RequestMapping(value="/goods")
	public ModelAndView goods(ModelMap modelMap,HttpServletRequest request){
		String path = Page.backGoods;
		try{
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载藏品页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path,modelMap);
	}
	
	@RequestMapping(value="/goodsPicture")
	public ModelAndView goodsPicture(ModelMap modelMap,HttpServletRequest request){
		String path = Page.backGoodsPicture;
		try{
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载产品库页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path,modelMap);
	}
	
	
	@RequestMapping(value="/goodsAddOrUpdate")
	public ModelAndView goodsAddOrUpdate(ModelMap modelMap,HttpServletRequest request,
			@RequestParam(required=false,value="id") Integer id){
		String path = Page.backGoodsAddOrUpdate;
		try{
			modelMap.put("id", id);
		}catch(Exception e){
			e.printStackTrace();
			path = Page.error;
			logger.error("LH_ERROR_加载添加或修改藏品页面出现异常_"+e.getMessage());
		}
		return new ModelAndView(path,modelMap);
	}
	
	@ResponseBody
	@RequestMapping(value="/addOrUpdateGoods", method=RequestMethod.POST)
	public JSONObject addOrUpdateGoods(@ModelAttribute BaseGoods goods,HttpServletRequest request){
		JSONObject json = new JSONObject();
		try {
			BaseAdmin admin = (BaseAdmin) request.getSession().getAttribute("admin");
			if(null == goods.getId()){//添加
				String goodsSn = CommonGenerator.getSerialByDate("g");
				goods.setGoodsSn(goodsSn);
				goods.setHits(0);
				goods.setScans(0);
				if(null != goods.getMainStatus()){
					goods.setMainStatus(75);
				}
				goods.setCreatedBy(admin.getUsername());
				goods.setCreatedAt(new Date());
				goodsService.insert(goods);
				String picPaths = goods.getPicPaths();
				if(Check.isNotNull(picPaths)){
					String filePaths[] = picPaths.split(",");
					BaseGoodsPicture goodsPicture = new BaseGoodsPicture();
					goodsPicture.setGoodsId(goods.getId());
					String serial = CommonGenerator.getSerialByDate("gp");
					goodsPicture.setSerial(serial);
					for(int i = 0 ; i < filePaths.length ;i++){
						goodsPicture.setPicPath(filePaths[i]);
						if(i == 0){
							goodsPicture.setIsCover(2);
						}else{
							goodsPicture.setIsCover(0);
						}
						goodsPictureService.insert(goodsPicture);
					}
				}
			}else{//修改
				goods.setUpdatedBy(admin.getUsername());
				goods.setUpdatedAt(new Date());
				goodsService.updateByPrimaryKeySelective(goods);
			}
			json.put("status", "success");
			json.put("id",goods.getId());
			json.put("msg", "操作成功");
		}catch (Exception e) {
			e.printStackTrace();
			json.put("msg", "操作失败");
			Result.catchError(e, logger, "LH_ERROR_添加或修改藏品出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getGoodsList",method=RequestMethod.POST)
	public JSONObject getGoodsList(HttpServletRequest request) {
		List<BaseGoods> goodsList = null;
		JSONObject json = new JSONObject();
		try {
			Map<String, Object> map = ActionUtil.getAllParam(request);
			goodsList = goodsService.selectListByCondition(map);
			Integer total = goodsService.selectCountByCondition(map);
			json.put("rows", goodsList);
			json.put("total", total);
			json.put("status", "success");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_加载藏品列表出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateGoodsDelete",method=RequestMethod.POST)
	public JSONObject updateGoodsDelete(HttpServletRequest request,
			@RequestParam(value="ids") String ids) {
		JSONObject json = new JSONObject();
		try {
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("ids", ids);
			map.put("table", Table.goods);
			map.put("username",admin.getUsername());
			utilService.updateDeletedNowByIds(map);
			json.put("status","success");
			json.put("msg","删除成功");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_删除藏品出现异常_", json);
		}
		return Result.success(json);
	}
	
	
	@ResponseBody
	@RequestMapping(value="/deleteGoodsThorough",method=RequestMethod.POST)
	public JSONObject deleteGoodsThorough(HttpServletRequest request,
			@RequestParam(value="ids") String ids) {
		JSONObject json = new JSONObject();
		try {
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("ids", ids);
			map.put("table", Table.goods);
			map.put("username",admin.getUsername());
			utilService.deleteByIds(map);
			json.put("status","success");
			json.put("msg","彻底删除成功");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_彻底删除藏品出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/updateGoodsRecover",method=RequestMethod.POST)
	public JSONObject updateGoodsRecover(HttpServletRequest request,
			@RequestParam(value="ids") String ids) {
		JSONObject json = new JSONObject();
		try {
			BaseAdmin admin = ActionUtil.checkSession4Admin(request.getSession());//验证session中的user，存在即返回
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("ids", ids);
			map.put("table", Table.goods);
			map.put("username",admin.getUsername());
			utilService.updateDeletedNullByIds(map);
			json.put("status","success");
			json.put("msg","恢复成功");
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_恢复藏品出现异常_", json);
		}
		return Result.success(json);
	}
	
	@ResponseBody
	@RequestMapping(value="/getGoods")
	public JSONArray getUser(HttpServletRequest request,@RequestParam Integer userId) {
		JSONArray array = new JSONArray();
		try {
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("userAllGoods", userId);
			List<BaseGoods> goodsList = goodsService.selectListByCondition(map);
			for(BaseGoods g : goodsList){
				JSONObject json = new JSONObject();
				json.put("id",g.getId());
				json.put("name",g.getGoodsName());
				array.add(json);
			}
		} catch (Exception e) {
			Result.catchError(e, logger, "LH_ERROR_获取用户商品出现异常_", array);
		}
		return array;
	}
	
}
